<template>
 <div> 
  <div style="padding: 20px 30px">
    <div v-if="isBank">
      <div class="title">
        <!-- <el-divider direction="vertical" /> -->
        电子账户 - 账户列表
      </div>

      <el-divider border-style="double" />

      <div class="kh-buttom">
        <el-button @click="addClick()" style="margin-left: 20px" type="primary"
          >开户</el-button
        >
      </div>

      <div class="title-qita">
        <el-divider direction="vertical" />
        金额信息
      </div>

      <div class="menoyInfo">
        <div class="menoy-color">
          <span>总计金额：</span>
          <span style="font-weight: 600; color: #1b1f26"
            >{{ totalMenoys }} 元</span
          >
        </div>
        <div class="menoy-color">
          <span>可用金额：</span>
          <span style="font-weight: 600; color: rgb(45, 140, 240)"
            >{{ kyMenoys }} 元</span
          >
        </div>
        <div class="menoy-color">
          <span>冻结金额：</span>
          <span style="font-weight: 600; color: rgb(255, 153, 0)"
            >{{ djMenoys }} 元</span
          >
        </div>
      </div>

      <div class="title-qita">
        <el-divider direction="vertical" />
        银行卡列表
      </div>
      <div style="margin-top: 20px">
        <el-table
          :data="bankData"
          border
          stripe
          :header-cell-style="{
            'text-align': 'center',
            color: '#515a6e',
            background: '#f8f8f9',
          }"
          :cell-style="{ 'text-align': 'center' }"
          style="font-size: 16px"
        >
          <el-table-column
            label="序号"
            type="index"
            width="60"
          ></el-table-column>
          <el-table-column label="银行名称" prop="bankName"></el-table-column>
          <el-table-column
            label="银行卡号"
            prop="bankCardNumber"
          ></el-table-column>
          
          <el-table-column label="银行行号" prop="bankNumber"></el-table-column>
          <el-table-column width="80" label="默认卡" prop="isDefault">
            <template #default="scope">
              <div>
                <el-switch
                  :disabled="scope.row.isDefault===0"
                  :model-value="scope.row.isDefault===0"
                  inline-prompt
                  active-text="是"
                  inactive-text="否"
                  @click="handle(value,scope.row)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column width="220" label="操作" fixed="right">
            <template #default="scope">
              <el-button
                style="font-size: 14px; border-radius: 8px"
                type="primary"
                size="small"
                @click="detail(scope.row.id)"
              >
                详情
              </el-button>
              <el-button
                style="font-size: 14px; border-radius: 8px"
                type="warning"
                size="small"
                @click="editClick(scope.row)"
              >
                修改
              </el-button>
              <el-button
                style="font-size: 14px; border-radius: 8px"
                type="danger"
                v-if="scope.row.isDefault===1"
                @click="delBank(scope)"
                size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
          ></el-table
        >
      </div>
      <el-dialog
        v-model="accountDialog"
        :title="isAdd ? '新增' : '修改'"
        center
        :close-on-click-modal="false"
        width="30%"
        :show-close="false"
        @close="dialogColse(accountRef)"
      >
        <el-form
          label-width="90px"
          :model="bank"
          :rules="bankRules"
          ref="accountRef"
        >
          <el-form-item label="银行名称:" prop="bankName">
            <el-input
              v-model="bank.bankName"
              placeholder="请输入银行名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="银行卡号:" prop="bankCardNumber">
            <el-input
              v-model="bank.bankCardNumber"
              placeholder="请输入银行卡号"
            ></el-input>
          </el-form-item>

          <el-form-item label="银行行号:" prop="bankNumber">
            <el-input
              v-model="bank.bankNumber"
              placeholder="请输入银行行号"
              maxlength="12"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submit(accountRef)">
              {{ isAdd ? "确认" : "修改" }}
            </el-button>
            <el-button @click="accountDialog = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div v-if="!isBank">
      <div class="title">
        <!-- <el-divider direction="vertical" /> -->
        账户列表-详情
      </div>
      <el-divider border-style="double" />

      <div class="title-qita">
        <el-divider direction="vertical" />
        金额信息
      </div>

      <div class="menoyInfo">
        <div class="menoy-color">
          <span>总计金额：</span>
          <span style="font-weight: 600; color: #1b1f26"
            >{{ totalMenoy }} 元</span
          >
        </div>
        <div class="menoy-color">
          <span>可用金额：</span>
          <span style="font-weight: 600; color: rgb(45, 140, 240)"
            >{{ kyMenoy }} 元</span
          >
        </div>
        <div class="menoy-color">
          <span>冻结金额：</span>
          <span style="font-weight: 600; color: rgb(255, 153, 0)"
            >{{ djMenoy }} 元</span
          >
        </div>
      </div>

      <div class="title-qita">
        <el-divider direction="vertical" />
        交易明细列表
      </div>

      <div class="buttom-bottom">
        <el-button
          @click="
            (ruchuDialog = true), (operType.type = 0), (isAccounting = true)
          "
          style="margin-left: 20px"
          type="primary"
          >入账</el-button
        >
        <el-button
          @click="
            (ruchuDialog = true), (operType.type = 1);
            isAccounting = false;
          "
          style="margin-left: 20px"
          type="warning"
          >出账</el-button
        >
        <el-button
          @click="(ruchuDialog = true), (operType.type = '2')"
          style="margin-left: 20px"
          type="danger"
          >冻结/解冻</el-button
        >
      </div>
      <div style="margin-top: 20px">
        <div style="margin-bottom: 20px">
          <div style="display: inline">
            <span>操作类型：</span>
            <el-select v-model="queryInfo.type" style="width: 100px">
              <el-option :label="'全部'" :value="''" />
              <el-option value="0" label="增加"></el-option>
              <el-option value="1" label="减少"></el-option>
              <el-option value="2" label="冻结"></el-option>
              <el-option value="3" label="解冻"></el-option>
            </el-select>
          </div>
          <div style="margin-left: 30px; display: inline">
            <span>操作时间：</span>
            <el-date-picker
              v-model="queryInfo.startTime"
              type="date"
              placeholder="请选择开始日期"
              format="YYYY-MM-DD"
              value-format="x"
            />-<el-date-picker
              v-model="queryInfo.endTime"
              type="date"
              placeholder="请选择结束日期"
              format="YYYY-MM-DD"
              value-format="x"
            />
          </div>
          <el-button @click="jymxSeach()" type="primary"> 查询</el-button>
          <el-button
            @click="
              queryInfo.pageNum = 1;
              queryInfo.pageSize = 10;
              queryInfo.type = '';
              queryInfo.startTime = '';
              queryInfo.endTime = '';
            "
            type="success"
          >
            重置</el-button
          >
          <el-button @click="goBack()" type="warning" plain> 返回</el-button>
        </div>
        <el-table
          :data="jymxData"
          border
          stripe
          :header-cell-style="{
            'text-align': 'center',
            color: '#515a6e',
            background: '#f8f8f9',
          }"
          :cell-style="{ 'text-align': 'center' }"
          style="font-size: 16px"
        >
          <el-table-column label="流水号" prop="id"></el-table-column>
          <el-table-column
            label="账户名称"
            prop="accountName"
          ></el-table-column>
          <el-table-column
            width="100"
            label="金额(元)"
            prop="tradeAmt"
          ></el-table-column>
          <el-table-column label="操作类型" prop="type">
            <template #default="scope">
              <span style="color: rgb(25, 190, 107)" v-if="scope.row.type == 0"
                >入金</span
              >
              <span style="color: red" v-if="scope.row.type == 1">出金</span>
              <span style="color: rgb(255, 153, 0)" v-if="scope.row.type == 2"
                >冻结</span
              >
              <span style="color: rgb(45, 140, 240)" v-if="scope.row.type == 3"
                >解冻</span
              >
            </template>
          </el-table-column>
          <el-table-column
            width="105"
            label="创建时间"
            prop="createTime"
          ></el-table-column>
          <el-table-column label="操作人" prop="opName"></el-table-column>
          <el-table-column label="备注" prop="message"></el-table-column>
          ></el-table
        >
        <div style="margin: 20px 2px 30px; border: ">
          <el-pagination
            background
            v-model:current-page="queryInfo.pageNum"
            v-model:page-size="queryInfo.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            style="justify-content: right"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryInfo.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <el-dialog
          v-model="ruchuDialog"
          :title="
            operType.type == 0
              ? '入账'
              : operType.type == 1
              ? '出账'
              : '冻结/解冻'
          "
          center
          :close-on-click-modal="false"
          width="30%"
          :show-close="false"
          @close="dialogClose(operTypeRef)"
        >
          <el-form :label-width="90" :model="operType" ref="operTypeRef">
            <el-form-item
              prop="kyMenoy"
              v-if="operType.type == 1"
              label="可用金额:"
              >{{ kyMenoy }}元</el-form-item
            >
            <el-form-item style="color: red" v-if="operType.type == 2"
              ><template #label>
                <span style="color: red">可用金额:</span> </template
              >{{ kyMenoy }}元</el-form-item
            >
            <el-form-item
              style="color: rgb(39, 9, 247)"
              v-if="operType.type == 3"
            >
              <template #label>
                <span style="color: rgb(39, 9, 247)">冻结金额:</span> </template
              >{{ djMenoy }}元</el-form-item
            >
            <el-form-item
              v-if="operType.type == 0"
              prop="tradeAmt"
              label="入账金额:"
              :rules="[
                {
                  required: true,
                  message: '请输入金额',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                placeholder="请输入入账金额"
                v-model="operType.tradeAmt"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="operType.type == 1"
              label="出账金额:"
              prop="tradeAmt"
              :rules="[
                {
                  required: true,
                  message: '请输入出账金额',
                  trigger: 'blur',
                },
                {
                  validator: czRules,
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                placeholder="请输入出账金额"
                v-model="operType.tradeAmt"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="operType.type == 2 || operType.type == 3"
              prop="tradeAmt"
              label="金额:"
              :rules="[
                {
                  required: true,
                  message: '请输入金额',
                  trigger: 'blur',
                },
                {
                  validator: cjjdRule,
                  trigger: 'blur',
                },
              ]"
            >
              <el-input placeholder="请输入金额" v-model="operType.tradeAmt">
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="operType.type == 2 || operType.type == 3"
              label="冻结解冻:"
              prop="type"
            >
              <el-select
                @change="cliclChange"
                v-model="operType.type"
                style="width: 240px"
              >
                <!-- <el-option value="" label="冻结"></el-option> -->
                <el-option value="2" label="冻结"></el-option>
                <el-option value="3" label="解冻"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item placeholder="请输入备注" label="备注:">
              <el-input
                v-model="operType.message"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="subType(operTypeRef)">
                {{ "确认" }}
              </el-button>
              <el-button @click="(ruchuDialog = false), (operType.type = '')"
                >取消</el-button
              >
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div></div>
</template>

<script>
import { reactive, toRefs, watch,h } from "vue";
import {
  add,
  update,
  del,
  list,
  menoyType,
  mxlist,
  updateDefault,
} from "../../api/account";

import { displayBoxInfo } from "@/utils/msg";
import { ElMessageBox, renderThumbStyle } from "element-plus";
export default {
  name: "account",

  setup() {
    const czRules = (rules, value, callback) => {
      if (value > data.kyMenoy) {
        callback(new Error("出账金额大于可用金额，操作失败"));
      } else {
        callback();
      }
    };

    const cjjdRule = (ruls, value, callback) => {
      if (data.operType.type == 2) {
        if (value > data.kyMenoy) {
          callback(new Error("冻结金额大于可用金额，操作失败"));
        } else {
          callback();
        }
      } else if (data.operType.type == 3) {
        if (value > data.djMenoy) {
          callback(new Error("解冻金额大于冻结金额，操作失败"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    let data = reactive({
      userId: JSON.parse(localStorage.getItem("userInfo")).id,
      bankId: "", //银行卡id
      dijd: false, //进行冻结，解冻操作
      isBank: true,
      totalMenoys: 0, //总金额
      kyMenoys: 0, //可用金额
      djMenoys: 0, //冻结金额
      totalMenoy: 0, //总金额
      kyMenoy: 0, //可用金额
      djMenoy: 0, //冻结金额
      isAdd: "",
      accountDialog: false,
      ruchuDialog: false, //入账，出账dailog弹框
      isAccounting: "", //是否入账
      accountRef: "",
      operTypeRef: "",
      bankData: "", //银行卡列表
      jymxData: "", //交易明细列表
      // 入账、出账、冻结、解冻操作
      operType: {
        userId: "",
        bankId: "",
        tradeAmt: "",
        type: "",
        message: "",
      },
      bank: {
        userId: "", //用户Id
        bankCardNumber: "", //银行卡号
        bankName: "", //银行名称
        bankNumber: "", //银行行号

      },
      queryInfo: {
        bankId: "", //银行卡id
        userId: JSON.parse(localStorage.getItem("userInfo")).id,
        pageNum: 1,
        pageSize: 10,
        total: 0,
        type: "",
        startTime: "",
        endTime: "",
      },
      bankRules: {
        bankCardNumber: [
          { required: true, message: "请输入银行卡号", trigger: "blur" },
          { pattern: /^\d+$/, message: "银行卡号只能是数字" },
        ],
        bankName: [
          { required: true,message: "请输入银行名称",trigger: "blur",}
          ],
        bankNumber: [
          { required: true, message: "请输入银行行号", trigger: "blur" },
          { pattern: /^\d+$/, message: "银行行号只能是数字" },
        ],
      },
    });
    //添加操作打开dialog弹框
    let addClick = () => {
      data.isAdd = true;
      data.accountDialog = true;
      data.bank = {
        userId: "", //用户id
        bankCardNumber: "", //银行卡号
        bankName: "", //银行名称
        bankNumber: "",
      };
    };

    //修改操作打开dialog弹框
    let editClick = (row) => {
      data.isAdd = false;
      data.accountDialog = true;
      // 深拷贝对象，避免直接引用导致列表数据实时同步
      data.bank = {
        id: row.id,
        userId: row.userId || data.userId,
        bankCardNumber: row.bankCardNumber || "",
        bankName: row.bankName || "",
        bankNumber: row.bankNumber || "",
        isDefault: row.isDefault,
      };
      console.log(data.bank.isDefault)
    };

    // 修改银行卡信息
    let submit = (formEI) => {
      if (!formEI) return;
      formEI.validate((valid, fileds) => {
        data.bank.userId = data.userId;
        if (valid) {
          //新增
          if (data.isAdd) {
            add(data.bank).then((res) => {
              displayBoxInfo(res.code, res.msg);
              if (res.code == 1) {
                data.accountDialog = false;
                backList();
              }
            });
          } else {
            //修改
            
            update(data.bank).then((res) => {
              displayBoxInfo(res.code, res.msg);
              if (res.code == 1) {
                data.accountDialog = false;
                backList();
              }
            });
          }
        } else {
          console.log(fileds);
        }
      });
    };

    //操作账户金额
    let subType = (formEI) => {
      if (!formEI) return;
      formEI.validate((valid, fileds) => {
        if (valid) {
          data.operType.userId = data.userId;
          data.operType.bankId = data.bankId;
          menoyType(data.operType).then((res) => {
            displayBoxInfo(res.code, res.msg);
            if (res.code == 1) {
              data.ruchuDialog = false;
              detail(data.operType.bankId);
            }
          });
        } else {
          console.log(fileds);
        }
      });
    };

    // 列表详情
    let detail = (id) => {
      data.queryInfo.type='';
      data.bankId = id;
      data.queryInfo.bankId = id;
      data.queryInfo.startTime='';
      data.queryInfo.endTime='';  
      mxlist(data.queryInfo).then((res) => {
        data.jymxData = res.data.records;
        data.queryInfo.total = Number(res.data.total);
        data.queryInfo.pageNum = res.data.pageNum;
        data.queryInfo.pageSize = res.data.pageSize;
        data.totalMenoy = res.data.totalMenoy;
        data.kyMenoy = res.data.kyMenoy;
        data.djMenoy = res.data.djMenoy;
      });
      data.isBank = false;
    };

    //返回操作
    let goBack = () => {
      data.isBank = true;
      data.kyMenoys=0;
      data.djMenoys=0;
      list({id:data.userId}).then((res) => {
        data.bankData = res.data;
        res.data.forEach((item) => {
          data.kyMenoys += item.kyMenoy;
          data.djMenoys += item.djMenoy;
        });
        data.totalMenoys = data.kyMenoys + data.djMenoys;
      });
    };
    

    // 银行卡列表信息
    let backList = () => {
      list({id:data.userId}).then((res) => {
        data.bankData = res.data;
         data.kyMenoys=0;
        data.djMenoys=0;
        res.data.forEach((item) => {
          data.kyMenoys += item.kyMenoy;
          data.djMenoys += item.djMenoy;
        });
        data.totalMenoys = data.kyMenoys + data.djMenoys;
      });
    };
    backList();

    // 交易明细查询条件
    let jymxSeach = () => {

      if (data.queryInfo.endTime == null) {
        data.queryInfo.endTime = "";

      }else if(data.queryInfo.endTime!=''){
    
        data.queryInfo.endTime = Number(data.queryInfo.endTime) +43200000-1;
      }

      if (data.queryInfo.startTime == null) {
        data.queryInfo.startTime = "";
      }
      mxlist(data.queryInfo).then((res) => {
        data.jymxData = res.data.records;
        data.queryInfo.total = Number(res.data.total);
        data.queryInfo.pageNum = res.data.pageNum;
        data.queryInfo.pageSize = res.data.pageSize;
        data.totalMenoy = res.data.totalMenoy;
        data.kyMenoy = res.data.kyMenoy;
        data.djMenoy = res.data.djMenoy;
      });
    };

    //删除银行卡信息
    let delBank = (scope) => {
      console.log(scope.row.id)
      del({ id: scope.row.id }).then((res) => {
        displayBoxInfo(res.code, res.msg);
        if (res.code == 1) {
          backList();
        }
      });
    };

    // 修改默认账户
    let handle = (value,row) => {
      //如果已经是默认卡直接返回 
      if(row.isDefault===0) return;
             ElMessageBox.confirm(
        h("p", null, [
          h("span", null, "确定要将："),
          h("i", { style: "color:red" }, row.bankName),
          h("i", { style: "color:red" }, "---"),
          h("i", { style: "color:red" }, row.bankCardNumber),
          h("span", null, " 设为默认银行卡吗"),
        ]),
        "提示"
      ) .then(() => {
          updateDefault({ id: row.id }).then((res) => {
           displayBoxInfo(res.code, res.msg);
           if(res.code==1){backList();}
          });
        })
        .catch((error) => {});
    };

    
    let dialogClose = (formEl) => {
      for (let key in data.operType) {
        if (key != "userId" || key != "bankId") {
          data.operType[key] = "";
        }
      }
      if (!formEl) return;
      formEl.resetFields();
    };

    //关闭弹框,实现重置和清除校验结果
    let dialogColse = (formEl) => {
      if (!formEl) return;
      formEl.resetFields();
    };

    //监听type的变化
    let cliclChange = (value) => {
      data.operType.type = value;
    };

    //监听 pagesize 改变的事件
    let handleSizeChange = (newSize) => {
      data.queryInfo.pageSize = newSize;
      jymxSeach();
    };
    let handleCurrentChange = (newNum) => {
      data.queryInfo.pageNum = newNum;
      jymxSeach();
    };

    return {
      ...toRefs(data),
      delBank,
      addClick,
      editClick,
      dialogColse,
      backList,
      submit,
      handleSizeChange,
      handleCurrentChange,
      detail,
      jymxSeach,
      subType,
      handle,
      dialogClose,
      czRules,
      cliclChange,
      cjjdRule,
      goBack,
    };
  },
};
</script>

<style scoped>
.title {
  color: #2d8cf0;
  font-weight: 600;
  font-size: 18px;
  margin: 0 0 10px 0px;
  line-height: 18px;
  margin-bottom: 20px;
}

.el-divider--vertical {
  border-left: 6px solid #2d8cf0;
  /* margin-bottom: 20px */
}

.kh-buttom {
  background-color: #eff6ff;
  border-radius: 8px;
  padding: 20px 0;
  margin-bottom: 12px;
  /* margin-left:20px */
}

.buttom-bottom {
  background-color: #eff6ff;
  box-shadow: 0 0 5px 5px hsla(0, 0%, 78.4%, 0.3);
  border-radius: 8px;
  padding: 20px 0px;
  margin: 30px 0px;
}

.menoyInfo {
  display: flex;
  justify-content: space-between;
  box-shadow: 0 0 5px 5px hsla(0, 0%, 78.4%, 0.3);
  margin-top: 12px;
  padding: 32px 52px 32px 32px;
  border-radius: 8px;
  background-color: #fff;
}

/* .menoyInfo > div {
  display: inline-block;
  margin-right: 200px;
} */

.menoy-color {
  color: #515a6e;
  font-size: 14px;
}

.title-qita {
  font-size: 16px;
  /* color: #010101; */
  font-weight: 600;
  margin: 0 0 10px 0px;
  margin: 25px 0 10px 0;
  line-height: 16px;
}

::v-deep .el-dialog__header {
  border-bottom: 1px solid #e8eaec !important;
  font-weight: 500;
  padding: 20px 30px;
  background: #fbfbfa;
  border-radius: 8px 8px 0px 0px;
  /* margin-bottom: 25px; */
  margin-right: 0 !important;
}
::v-deep .el-dialog__footer {
  border: 1px solid #e8eaec;
  font-weight: 700;
  background: #fbfbfa;
  border-radius: 0px 0px 8px 8px;
  padding-top: 20px;
}

.el-form-item__error {
  left: 12px;
  font-size: 14px;
}
</style>